﻿using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using CS.Diagnostics;
using CS.Scheduling;

namespace CS.Beehive
{
    /// <summary>
    /// Channel断开清理任务
    /// </summary>
    public class ChannelDisconnectMission : Mission
    {

        private readonly ConcurrentQueue<ChannelDisconnectEventArgs> _queue = new ConcurrentQueue<ChannelDisconnectEventArgs>();

        //private Stopwatch sw = new Stopwatch();


        /// <summary>
        /// 加入到清理队列
        /// </summary>
        /// <param name="args"></param>
        public void Add(ChannelDisconnectEventArgs args)
        {
            _queue.Enqueue(args);
        }


        protected override void Execute()
        {
            if (_queue.Count == 0) return;
            //sw.Reset();
            //sw.Start();
            //Console.Write(_queue.Count);
            foreach (var args in _queue.TakeWhile(args => args.Channel == null || args.Channel.ActiveTickCount + args.Delay < Environment.TickCount))
            {
                ChannelDisconnectEventArgs channel;
                if (!_queue.TryDequeue(out channel)) continue;
                channel.Channel.Disconnect();
                args.Channel = null;
            }
            //sw.Stop();
            //Console.WriteLine("TS:{0:HH:mm:ss ffffff}", sw.Elapsed);
        }




    }
}